import React, { useState } from 'react';
import { Form, Input, Button, Select, Card, message, Modal } from 'antd';
import { UserOutlined, LockOutlined, PhoneOutlined, MailOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import './index.less';

const { Option } = Select;

const LoginPage = () => {
  const [loading, setLoading] = useState(false);
  const [role, setRole] = useState('doctor');
  const [registerVisible, setRegisterVisible] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const onFinish = async () => {
    setLoading(true);
    try {
      message.success('登录成功');
      switch(role) {
        case 'doctor':
          navigate('/doctor/dashboard');
          break;
        case 'admin':
          navigate('/admin/dashboard');
          break;
        default:
          navigate('/patient/dashboard');
      }
    } catch (error) {
      console.error('登录出错:', error);
      message.error('登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
    }
  };

  const sendVerificationCode = () => {
    if (countdown > 0) return;
    
    const phone = form.getFieldValue('phone');
    if (!phone) {
      message.error('请输入手机号');
      return;
    }

    setCountdown(60);
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) clearInterval(timer);
        return prev - 1;
      });
    }, 1000);

    message.success('验证码已发送');
  };

  const handleRegister = async () => {
    try {
      // 调用注册API
      message.success('注册成功');
      setRegisterVisible(false);
      form.resetFields();
    } catch (error) {
      message.error(error,'注册失败');
    }
  };

  return (
    <div className="login-container">
      <Card title="COPD管理系统登录" className="login-card">
        <Form onFinish={onFinish}>
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item
            name="role"
            initialValue={role}
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select onChange={(value) => setRole(value)}>
              <Option value="doctor">医生</Option>
              <Option value="patient">患者</Option>
              <Option value="admin">管理员</Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              登录
            </Button>
          </Form.Item>
        </Form>

        <Button 
          type="link" 
          onClick={() => setRegisterVisible(true)}
          style={{ marginTop: 16 }}
        >
          没有账号？立即注册
        </Button>
      </Card>

      <Modal
        title="用户注册"
        visible={registerVisible}
        onCancel={() => {
          setRegisterVisible(false);
          form.resetFields();
        }}
        footer={null}
        destroyOnClose
      >
        <Form form={form} onFinish={handleRegister}>
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input prefix={<PhoneOutlined />} placeholder="手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <div style={{ display: 'flex', gap: 8 }}>
              <Input prefix={<MailOutlined />} placeholder="验证码" />
              <Button onClick={sendVerificationCode} disabled={countdown > 0}>
                {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="确认密码" />
          </Form.Item>

          <Form.Item
            name="role"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="选择角色">
              <Option value="patient">患者</Option>
              <Option value="doctor">医生</Option>
              <Option value="admin">管理员</Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              注册
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default LoginPage;